package com.aptemo.webetek.server.handlers;

import com.aptemo.webetek.client.commands.Action;
import com.aptemo.webetek.client.commands.impl.GetCurrentUserDetailsAction;
import com.aptemo.webetek.client.enums.EnumUserRole;
import com.aptemo.webetek.client.exceptions.BackendException;
import com.aptemo.webetek.client.exceptions.WebetekLoginException;
import com.aptemo.webetek.client.exceptions.BackendException.EErrorCodes;
import com.aptemo.webetek.server.data.WebetekUser;
import com.aptemo.webetek.server.datastore.DataStoreAPI;
import com.aptemo.webetek.shared.UserBean;
import com.google.appengine.api.users.UserServiceFactory;

public class CurrentUserDetailsHandler
		extends ActionHandler<GetCurrentUserDetailsAction, UserBean>
{

	public CurrentUserDetailsHandler(DataStoreAPI dataService)
	{
		super(dataService);
	}

	public Class<? extends Action<?>> getActionType()
	{
		return GetCurrentUserDetailsAction.class;
	}

	@Override
	public UserBean invoke(GetCurrentUserDetailsAction action) throws BackendException, WebetekLoginException
	{
		utils.checkLogin();

		WebetekUser user = utils.getCurrentUser(action.getTeamId());

		UserBean ub;
		if (userService.isUserAdmin() && user == null)
		{
			ub = new UserBean(userService.getCurrentUser().getEmail());
		}
		else if (user == null)
		{
			throw new BackendException(EErrorCodes.NOT_TEAM_MEMBER);
		}
		else
		{
			ub = user.toBean();			
		}

		if (UserServiceFactory.getUserService().isUserAdmin())
		{
			ub.setRole(EnumUserRole.ADMIN);
		}

		return ub;
	}
}
